<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use think\facade\Cache;
use think\response\Json;

class RafflePrize extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\RafflePrize';

    //自定义方法排序
    protected array $sort = ['id' => 'asc'];

    public function index(): string
    {
        return Builder::Table()
            ->addColumn(['field' => 'id', 'title' => 'ID', 'sort' => true, 'width' => 80])
            ->addColumn(['field' => 'title', 'title' => '名称', 'modify' => '2,input'])
            ->addColumn(['field' => 'icon', 'title' => '图标', 'modify' => '2,img', 'templet' => '#iconTpl'])
            ->addColumn(['field' => 'amount', 'title' => '金额', 'modify' => '2,number'])
            ->addColumn(['field' => 'odds', 'title' => '中奖概率', 'modify' => '2,ratio', 'templet' => '{{(d.odds*100).toFixed(2)}}%'])
            ->addColumn(['field' => 'update_time', 'title' => '更新时间'])
            ->addColumn(['fixed' => 'right', 'title' => '操作', 'align' => 'center', 'toolbar' => '#barDemo', 'width' => 80])
            ->addRightButtons(['edit' => ['size' => '50%']])
            ->fetch();
    }

    public function edit($id = '', $tpl = 'raffle_prize/edit', $info = ''): string
    {
        return parent::edit($id, $tpl, $info);
    }

    public function save($param = [], $model = false): Json
    {
        $param = $this->request->post();
        if (!empty($param['odds'])) {
            $param['odds'] = $param['odds'] / 100;
        }
        if ($param['id'] != 1) {
            $one = $this->model::where(['id' => 1])->find();
            $max = round($one->odds + $param['old_odds'], 2);
            if ($param['odds'] > $max) {
                $max_rate = $max * 100;
                return json(['code' => -1, 'msg' => '当前可设置最大概率为' . $max_rate . '%']);
            }
            $change = round($param['odds'] - $param['old_odds'], 2);
            $one->odds = round($one->odds - $change, 2);
            $one->save();
        }
        Cache::delete('raffle_prize');

        return parent::save($param, $model);
    }
}